<template>
    <div class="silder-bar-box" id="silder-bar-page">
        <div class="logo-img" :class="[brevity && 'small-img']">
            <!-- <img :src="logoImg" @click="goHome()"> -->
            <div class="logo-image" :style="{ backgroundImage: `url(${logoImg})` }" @click="goHome()"></div>
        </div>
        <div class="silder-nav-body">
            <el-scrollbar :noresize="true" ref="silderScroll" v-if="!!isLogin">

                <el-tree :data="getCurrentNavList" highlight-current @node-click="nodeClick" node-key="key"
                    :expand-on-click-node="false" ref="treeRef" @node-expand="nodeExpand">
                    <template #default="{ node, data, index }">
                        <span class="custom-tree-node" v-if="data.level < 3">
                            <el-tooltip :content="node.label" placement="right" :disabled="!brevity" effect="light"
                                v-if="data.level === 1">
                                <svg class="svg-icon" aria-hidden="true">
                                    <use v-bind:xlink:href="`#${index == isActiveItem ? data.iconActive : data.icon}`">
                                    </use>
                                </svg>
                            </el-tooltip>
                            <svg class="svg-icon" v-else-if="data.level === 2">
                                <use xlink:href="#keowledge-quanbuwenku-xuanzhong"></use>
                            </svg>
                            <span class="name">{{ data.label }}</span>
                        </span>
                        <div class="custom-tree-node-child" v-else
                            :class="[hidePopover && popoverData.id == data.id && 'custom-active']">
                            <svg class="svg-icon" aria-hidden="true">
                                <use v-bind:xlink:href="getIcon(data.type, data.nameSuffix)"></use>
                            </svg>
                            <div class="node-info">
                                <div v-tooltip-auto-show>
                                    <el-tooltip :content="data.name" effect="light">
                                        <div class="name">{{ data.name }}</div>
                                    </el-tooltip>
                                </div>
                                <div class="time">{{ data.createTime }}</div>
                            </div>
                            <div class="action-box"
                                :class="[!$permissionRole(['document_auth_settings', 'document_add', 'document_update', 'document_down', 'document_share', 'document_delete', 'document_move'], data.dcIdentifying) && 'no-auth-aciton-box']">
                                <svg class="action-icon share" v-if="data.share">
                                    <use xlink:href="#keowledge-a-zu5046"></use>
                                </svg>
                                <i class="knowledge-iconfont action-icon more keowledge-gengduocaozuo"
                                    :ref="(el) => setMoreRef(el, data)" @click.stop="moreClick(node, data)"></i>
                            </div>
                        </div>
                    </template>
                </el-tree>


                <template v-for="(item, index) in getCurrentNavList" :key="index">
                    <div class="silder-item"
                        :class="[index == isActiveItem && (!isCheckKnow || !item.isOpen || brevity) && 'silder-item-active']"
                        @click="toPath(item)">
                        <div class="icon-list" v-if="!brevity && !isHideCol">
                            <svg class="icon" v-if="item.isList && item.list.length != 0"
                                @click.stop="changeItemOpen(item)">
                                <use
                                    v-bind:xlink:href="`#${!item.isOpen ? 'keowledge-xiala-shouqi' : 'keowledge-xiala-zhankai'}`">
                                </use>
                            </svg>
                        </div>
                        <div class="title">
                            <el-tooltip :content="item.label" placement="right" :disabled="!brevity" effect="light">
                                <svg class="svg-icon" aria-hidden="true">
                                    <use v-bind:xlink:href="`#${index == isActiveItem ? item.iconActive : item.icon}`"></use>
                                </svg>
                            </el-tooltip>
                            <span v-if="!brevity">{{ item.label }}</span>
                        </div>
                    </div>
                    <div class="list-box" v-if="item.isList && !brevity" :class="[item.isOpen && 'list-box-open']">
                        <div class="list-items">
                            <div class="list-item" v-for="(cItem, cIndex) in item.list" :key="cIndex"
                                :class="[isCheckKnow == cItem.id && index == isActiveItem && 'silder-item-active']"
                                @click="goToKnow(cItem, item, index)">
                                <svg class="svg-icon">
                                    <use xlink:href="#keowledge-quanbuwenku-xuanzhong"></use>
                                </svg>
                                <span>{{ cItem.name }}</span>
                            </div>
                        </div>
                    </div>
                </template>
            </el-scrollbar>
            <div class="no-login-box" v-if="!isLogin && !brevity">
                <img :src="noLogin">
                <div class="login-title">{{ $t('message.text.noLogin') }}</div>
                <div class="login-tips">{{ $t('message.text.loginAfter') }}</div>
                <el-button type="primary" class="login-button" @click="goLogin">{{ $t('message.buttons.login') }}
                </el-button>
            </div>
        </div>
    </div>

    <!-- 更多操作的选项 -->
    <el-popover ref="morePopoverRef" :virtual-ref="morebuttonRef" trigger="click" :visible="hidePopover"
        virtual-triggering placement="right-start" popper-class="more-popover-action">
        <el-scrollbar>
            <div class="more-lists" v-click-outside="onClickOutside">
                <template v-for="(item, num) in getCurMoreAction" :key="num">
                    <div v-if="item.type != 'line'" class="more-item" @click="moreAction(item)"
                        :ref="(el) => setMoreTypeRef(el, item)">
                        <svg class="svg-icon">
                            <use v-bind:xlink:href="`#${item.isActive ? item.iconActive : item.icon}`"></use>
                        </svg>
                        <span class="name">{{ item.label }}</span>
                        <svg class="arrow-icon" v-if="item.isArrow">
                            <use xlink:href="#keowledge-a-zu4701"></use>
                        </svg>
                    </div>
                    <div v-else class="more-line"></div>
                </template>
            </div>
        </el-scrollbar>
    </el-popover>
    <!-- 新建的虚拟弹窗 -->
    <el-popover ref="addPopoverRef" placement="right-start" :virtual-ref="addButPopoverRef" trigger="click"
        virtual-triggering :visible="addPopover" popper-class="more-popover-action">
        <el-scrollbar>
            <div class="more-lists">
                <template v-for="(item, index) in addActionList" :key="index">
                    <div class="more-item" @click="moreAction(item)">
                        <svg class="svg-icon">
                            <use v-bind:xlink:href="`#${item.icon}`"></use>
                        </svg>
                        <span class="name">{{ $t(item.label) }}</span>
                    </div>
                </template>
            </div>
        </el-scrollbar>
    </el-popover>
    <!-- 导入的虚拟弹窗 -->
    <el-popover ref="importPopoverRef" placement="right-start" :virtual-ref="uploadButPopoverRef" trigger="click"
        virtual-triggering :visible="uploadPopover" popper-class="more-popover-action">
        <el-scrollbar>
            <div class="more-lists">
                <template v-for="(item, index) in uploadActionList" :key="index">
                    <div class="more-item" @click="moreAction(item)">
                        <svg class="svg-icon">
                            <use v-bind:xlink:href="`#${item.icon}`"></use>
                        </svg>
                        <span class="name">{{ $t(item.label) }}</span>
                    </div>
                </template>
            </div>
        </el-scrollbar>
    </el-popover>
    <!-- 下载的虚拟弹窗 -->
    <!-- :placement="clickTopBar?'bottom':'right-start'" -->
    <el-popover ref="importPopoverRef" placement="right-start" :virtual-ref="downloadButPopoverRef" trigger="click"
        virtual-triggering :visible="downloadPopover" popper-class="more-popover-action">
        <el-scrollbar>
            <div class="more-lists">
                <template v-for="(item, index) in downloadActionList" :key="index">
                    <div class="more-item" @click="moreAction(item)" v-if="item.show">
                        <svg class="svg-icon">
                            <use v-bind:xlink:href="`#${item.icon}`"></use>
                        </svg>
                        <span class="name">{{ $t(item.label) }}</span>
                    </div>
                </template>
            </div>
        </el-scrollbar>
    </el-popover>
    <el-popover ref="popoverRef" :virtual-ref="tagRef" trigger="click" virtual-triggering :visible="tagPopover"
        placement="right-start" popper-class="tag-popover-action">
        <div class="tag-body-box" v-click-outside="onClickTagOutside" v-loading="labelLoading">
            <div class="tag-input-box" :class="[searchTagFocus && 'tag-input-foucs']">
                <el-input v-model="searchTag" @focus="inputFoucs" @blur="inputBlur"
                    :placeholder="$t('message.placeholder.searchLabel')"></el-input>
            </div>
            <el-scrollbar ref="tagListRef">
                <div class="tag-lists">
                    <div v-for="(item, index) in fileterTagList" :key="index" class="tag-item"
                        @click="bindDocLabel(item)">
                        <div class="tag-colour" :style="{ 'background-color': item.colour }"></div>
                        <div></div>
                        <div class="tag-name-box" v-tooltip-auto-show>
                            <el-tooltip :content="item.tagName" effect="light">
                                <div class="tag-name">{{ item.tagName }}</div>
                            </el-tooltip>
                        </div>
                        <svg class="check-icon">
                            <use
                                v-bind:xlink:href="`#${item.isSelect ? 'keowledge-a-zu3739' : 'keowledge-a-juxing2862biankuang'}`">
                            </use>
                        </svg>
                    </div>
                    <div class="more-loading-box" v-if="labelPage.current != 1 && moreLoading">
                        <img class="refresh-img" src="../../assets/common/loading-page.gif">
                    </div>
                </div>
            </el-scrollbar>
            <jvs-empty v-if="fileterTagList.length == 0" text="" size="160px" style="margin-top:20px;"></jvs-empty>
        </div>
    </el-popover>
    <createFolder ref="createFolderRef" @createSuccess="createSuccess"></createFolder>
    <ReName ref="reNameRef" @changeFileName="changeItemKeyVal"></ReName>
    <SelectKnow ref="selectKnowRef" :title="$t('message.text.moveTitle')" @callBack="getCheckedFile"></SelectKnow>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance, computed, watch, nextTick } from 'vue'
import type { ComponentInternalInstance } from 'vue'
import MindElixir from "mind-elixir";
import { ClickOutside as vClickOutside, ElTree } from 'element-plus'
import { useHookI18n } from '@/hooks/i18n'
import { useRouter, useRoute } from "vue-router"
import logo from '@/assets/images/logo.png'
import icon from '@/assets/images/icon.ico'
import noLogin from '@/assets/images/common/noLogin.png'
import useUserInfoStore from '@/store/userInfo';
import {
    getDcLibraryList,
    knowledgesOwner,
    getLibTree,
    dclibRecycle,
    fileDictoryDec,
    downLoadFile,
    downLoadFileD,
    fileDown,
    locationOther
} from '@/api/knowledge'
import { downLoad, generateUUID, copyText } from "@/utils/util";
import { $permissionRole } from "@/utils/role";
import {
    ADD_ACTION_LIST, DOWNLOAD_ACTION_LIST, MORE_ACTION_LIST, NAV_LIST, SET_NAV_LIST, UPLOAD_ACTION_LIST
} from "@/const/data";
import useKnowledgeStore from "@/store/knowledge";
import * as O from "@/utils/uniqueId";
import createFolder from '@/views/common/createFolder.vue'
import ReName from '@/views/common/reName.vue'
import SelectKnow from '@/views/selectKnow/index.vue'
import useCommonStore from "@/store/common";
import { preview, docStar } from "@/api/common";
import { exportExcel } from "@/utils/export.ts";
import exampleData from "@/components/xmind-map/config/exampleData";
import MindMaps from "simple-mind-map";
import { setDomStyle } from "@/utils/common";
import { editDocTag, getTagAlls } from "@/api/tag";

const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const { $t } = useHookI18n()
const router = useRouter();
const route = useRoute()
const userStore = useUserInfoStore()
const commonStore = useCommonStore()
const emit = defineEmits([""])
const props = defineProps({
    brevity: {
        type: Boolean,
        default: false
    }
})
const hidePopover = ref(false)
const popoverData = ref({
    type: '',
    id: '',
    parentId: '',
    nameSuffix: '',
    shareTimeType: '',
    dcIdentifying: [],
    share: false,
})
const morebuttonRefs = ref<any>({})
const morebuttonRef = ref()
function setMoreRef(el: any, data: any) {
    if (el) {
        morebuttonRefs.value[data.id] = el
    }
}
function moreClick(_node: any, data: any) {
    // 重新赋值virtual-ref绑定的
    morebuttonRef.value = morebuttonRefs.value[data.id]
    // 显示popover
    hidePopover.value = true
    // 赋值
    popoverData.value = data
    if (!popoverData.value.shareTimeType) popoverData.value.shareTimeType = 'PERPETUAL'
}
const addPopover = ref(false)
const uploadPopover = ref(false)
const moreActionButRef = ref<any>({})
const tagPopover = ref(false)
// 下载的虚拟弹窗
const downloadPopover = ref(false)
const selectKnowRef = ref()
const moreActionList = MORE_ACTION_LIST
const addActionList = ref(ADD_ACTION_LIST)
const uploadActionList = UPLOAD_ACTION_LIST
function createSuccess(val: string) {
    // changeItemKeyVal('valChange', {
    //     id: val.id,
    //     key: 'name',
    //     changeVal: val.name
    // })
    // if (val.type == 'url_address') {
    //     changeItemKeyVal('valChange', {
    //         id: val.id,
    //         key: 'urlAddress',
    //         urlAddress: val.urlAddress
    //     })
    // }
}
function changeItemKeyVal(type: string, val: { id: any; key: string; changeVal: any; }) {
    // switch (type) {
    //     case 'valChange':
    //         treeData.value.forEach(item => {
    //             if (item.id == val.id) {
    //                 item[val.key] = val.changeVal
    //             }
    //         })
    //         break;
    //
    //     default:
    //         break;
    // }
}
function getCheckedFile(item: any) {
    locationOther({
        id: popoverData.value.id,
        knowledgeId: item.knowledgeId || item.id,
        parentId: item.id
    }).then(res => {
        if (res.data.code == 0) {
            proxy.$onePrompt.$oneNotify({
                title: $t('message.prompt'),
                message: $t('message.message.moveSuccess'),
                type: 'success',
                position: 'bottom-right',
            })
            // init()
        }
    })
}

const getCurMoreAction = computed(() => {
    let arr: any[] = []
    moreActionList.forEach((item) => {
        item.isActive = false
        if (item.langLabel) {
            item.label = $t(item.langLabel)
        }
        if (item.label == $t('message.buttons.download')) {
            if (['document_html', 'xmind'].indexOf(popoverData.value.type) != -1) {
                item.isArrow = true
            } else {
                item.isArrow = false
            }
        }
        if (item.type == 'collect') {
            item.label = $t('message.buttons.collect')
            item.isActive = popoverData.value[item.propKey]
            if (item.isActive) {
                item.label = $t('message.buttons.unCollect')
            }
        }
        if (!item.includeFileType && !item.notIncludeFileType) {
            arr.push(item)
        } else if (item.includeFileType && item.includeFileType.indexOf(popoverData.value.type) != -1) {
            if (item.label == $t('message.buttons.unZip')) {
                if (['zip'].indexOf(popoverData.value.nameSuffix) != -1) {
                    arr.push(item)
                }
            } else {
                arr.push(item)
            }
        } else if (item.notIncludeFileType && item.notIncludeFileType.indexOf(popoverData.value.type) == -1) {
            if (item.label == $t('message.buttons.share')) {
                if (popoverData.value.share) {
                    arr.push(item)
                }
            } else {
                arr.push(item)
            }
        }
    })
    arr = arr.filter((item) => {
        if (!item.authName || item.authName.length == 0) {
            return true
        }
        return $permissionRole(item.authName, popoverData.value.dcIdentifying)
    })
    return arr
})
// 记录当前的操作是那一项
const currAction = ref({})
const clickTopBar = ref(false)
const labelLoading = ref(false)
const labelList = ref<any>([])
const tagRef = ref()
const addButPopoverRef = ref()
const uploadButPopoverRef = ref()
const createFolderRef = ref()
const knowledgeType = ref('')
const knowStore = useKnowledgeStore()
const dcLibrary = ref({
    name: '',
    dcIdentifying: []
})
const breadPath = ref<object[]>()
const enterFolderId = ref('')
const reNameRef = ref()
const downloadButPopoverRef = ref()
const downloadActionList = ref(DOWNLOAD_ACTION_LIST)
// 记录当前选中的树节点
const checkNode = ref<any>({})
const tagListRef = ref()
const tagScrollTop = ref(0)
// 判定当前文件的类型是否可以编辑
function editType(item: any): string {
    let type = ''
    if (["document_map", "document_xlsx", "document_flow", "document_html", "md", 'xmind'].indexOf(item.type) > -1) {
        type = 'editor'
    } else if (['docx', 'xlsx', 'pptx', 'csv'].indexOf(item.nameSuffix) != -1) {
        type = 'office'
    } else {
        type = 'directory'
    }
    return type
}

function sourceFileDownload(downItem: any) {
    proxy.$openJvsMessage({
        message: $t('message.message.fileDownloading')
    })
    let storeDownItem = {
        id: downItem.id,
        name: downItem.name,
        isFinish: false,
        downTime: new Date().getTime()
    }
    let soteDownList = commonStore.downFileList
    soteDownList.push(storeDownItem)
    commonStore.setDownLoadFileList(soteDownList)
    let fun = downLoadFile
    if (['directory', 'knowledge'].indexOf(downItem.type) != -1) {
        fun = downLoadFileD
    }
    fun({
        id: downItem.id,
        timestamp: new Date().getTime()
    }, 'blob', () => { }).then(res => {
        downLoad(res, true, () => {
            soteDownList.forEach((item: any) => {
                if (item.downTime == storeDownItem.downTime) {
                    item.isFinish = true
                }
            })
            commonStore.setDownLoadFileList(soteDownList)
        }, () => { })
    })
}
async function downloadFileFun(downItem: any, downType: any) {
    let res: any, Dom: any
    proxy.$openJvsMessage({
        message: $t('message.message.fileDownloading')
    })
    let storeDownItem = {
        id: downItem.id,
        name: downItem.name,
        isFinish: false,
        downTime: new Date().getTime()
    }
    let soteDownList = commonStore.downFileList
    soteDownList.push(storeDownItem)
    commonStore.setDownLoadFileList(soteDownList)
    switch (downItem.type) {
        case 'document_html':
            fileDown(downType, downItem.id).then(res => {
                if (res.data.code == 0) {
                    let downloadElement = document.createElement('a')
                    downloadElement.href = res.data.data
                    downloadElement.download = downItem.name + (downItem.name.indexOf(downItem.nameSuffix) != -1 ? '' : ('.docx'))
                    downloadElement.target = '_blank'
                    document.body.appendChild(downloadElement)
                    downloadElement.click()
                    document.body.removeChild(downloadElement)
                    soteDownList.forEach((item) => {
                        if (item.downTime == storeDownItem.downTime) {
                            item.isFinish = true
                        }
                    })
                    commonStore.setDownLoadFileList(soteDownList)
                }
            }).catch((_err: any) => {
                soteDownList.forEach((item) => {
                    if (item.downTime == storeDownItem.downTime) {
                        item.isFinish = true
                    }
                })
                commonStore.setDownLoadFileList(soteDownList)
            })
            break;
        case 'document_xlsx':
            let resData = []
            res = await preview(downItem.id)
            if (res.data.data.content && res.data.data.content.startsWith("{")) {
                resData = JSON.parse(JSON.parse(res.data.data.content).content);
            }
            exportExcel(resData, downItem.name, function () {
                soteDownList.forEach((item) => {
                    if (item.downTime == storeDownItem.downTime) {
                        item.isFinish = true
                    }
                })
                commonStore.setDownLoadFileList(soteDownList)
                proxy.$notify({
                    title: $t('message.downloadTitle'),
                    message: $t('message.message.downloadSuccess'),
                    type: 'success',
                    position: 'bottom-right'
                })
            })
            break;
        case 'xmind':
            if (clickTopBar.value) {
                proxy.$eventBus.$emit("menu-down-file", downType.replace('export-', ''))
                // fileViewShowRef.value?.downFile(downType.replace('export-', ''))
            } else {
                res = await preview(downItem.id)
                let contentData = JSON.parse(JSON.stringify(exampleData))
                if (res.data.data.content && res.data.data.content.startsWith("{")) {
                    const contentObj = JSON.parse(res.data.data.content)
                    contentData = JSON.parse(contentObj.content)
                } else if (res.data.data.content && res.data.data.content.startsWith("[")) {
                    contentData.root = MindMap.xmind.transformXmind(res.data.data.content)
                } else {
                    contentData.root = {
                        children: [],
                        data: {
                            text: '根节点',
                            expand: true,
                            isActive: false
                        }
                    }
                }
                Dom = await setDomStyle('downloadXmind')
                document.body.appendChild(Dom)
                const { root, layout, theme, view } = contentData
                const MindMap = new MindMaps({
                    el: Dom,
                    data: root,
                    layout: layout,
                    theme: theme.template,
                    themeConfig: theme.config,
                    viewData: view
                })
                setTimeout(async () => {
                    if (downType.replace('export-', '') === 'svg') {
                        await MindMap.export(downType.replace('export-', ''), true, downItem.name, `* {
                            margin: 0;
                            padding: 0;
                            box-sizing: border-box;
                        }`)
                    } else {
                        await MindMap.export(downType.replace('export-', ''), true, downItem.name, true)
                    }
                    soteDownList.forEach((item) => {
                        if (item.downTime == storeDownItem.downTime) {
                            item.isFinish = true
                        }
                    })
                    commonStore.setDownLoadFileList(soteDownList)
                    document.body.removeChild(Dom)
                }, 200)
            }
            break;
        case 'document_map':
            res = await preview(downItem.id)
            let type, content;
            const MindElixirList = [MindElixir.LEFT, MindElixir.RIGHT, MindElixir.SIDE]
            if (res.data.data.content && res.data.data.content.startsWith("{")) {
                let resData = JSON.parse(res.data.data.content).content;
                content = JSON.parse(resData);
            }
            if (res.data.data.otherJson) {
                type = JSON.parse(res.data.data.otherJson).type
            }
            Dom = setDomStyle('downloadMap')
            document.body.appendChild(Dom)
            const mindElixir = new MindElixir({
                locale: 'zh_CN',
                el: Dom,
                direction: MindElixirList[type],
                draggable: false, // 启用拖动
                contextMenu: false, // 启用右键菜单
                toolBar: true, // 启用工具栏
                nodeMenu: false, // 启用节点菜单
                keypress: false, // 启用快捷键
                editable: false // 可否编辑
            })
            setTimeout(async () => {
                const blob = await mindElixir.exportPng() // Get a Blob!
                document.body.removeChild(Dom)
                if (!blob) return
                const url = URL.createObjectURL(blob)
                const a = document.createElement('a')
                a.href = url
                a.download = `${downItem.name}.png`
                a.click()
                URL.revokeObjectURL(url)
                soteDownList.forEach((item) => {
                    if (item.downTime == storeDownItem.downTime) {
                        item.isFinish = true
                    }
                })
                commonStore.setDownLoadFileList(soteDownList)
            }, 50)
            if (!content || JSON.stringify(content) == '{}') {
                mindElixir.init(MindElixir.new('请输入文字'))
            } else {
                mindElixir.init(content)
            }
            break;
        default:
            break;
    }
}
// 发送收藏
function sendCollect(val: any) {
    docStar(val).then((res: any) => {
        if (res.data.code == 0) {
            proxy.$onePrompt.$oneNotify({
                title: $t('message.prompt'),
                message: $t('message.message.actionSuccess'),
                type: 'success',
                position: 'bottom-right'
            })
            changeItemKeyVal('valChange', {
                id: val,
                key: 'collectIs',
                changeVal: res.data.data
            })
        }
    })
}
const labelPage = ref({
    size: 20,
    current: 1,
    total: 0
})
const searchTag = ref('')
const searchTagFocus = ref(false)
const fileterTagList = computed(() => {
    return labelList.value.filter((item: { tagName: string | string[]; }) => {
        return item.tagName.indexOf(searchTag.value) != -1
    })
})
function onClickTagOutside() {
    tagPopover.value = false
}
function inputFoucs() {
    searchTagFocus.value = true
}

function inputBlur() {
    searchTagFocus.value = false
}
function bindDocLabel(item: any) {
    item.isSelect = !item.isSelect
    editDocTag({
        ...item,
        dcId: popoverData.value.id
    }).then(res => {
        if (res.data.code == 0) {
            let msg = $t('message.message.binLabelSuccess')
            if (!item.isSelect) {
                msg = $t('message.message.unbindLabelSuccess')
            }
            proxy.$onePrompt.$oneNotify({
                title: msg,
                type: "success",
                position: "bottom-right",
            });
        }
    })
}

const moreLoading = ref(false)
function getLabel() {
    moreLoading.value = true
    getTagAlls({
        dcId: popoverData.value.id,
        size: labelPage.value.size,
        current: labelPage.value.current
    }).then(res => {
        if (res.data.code == 0) {
            labelPage.value.total = res.data.data.total
            labelList.value.push(...res.data.data.records)
            labelLoading.value = false
            moreLoading.value = false
        }
    })
}
// 更多操作
function moreAction(item: any) {
    uploadPopover.value = false
    downloadPopover.value = false
    addPopover.value = false
    currAction.value = item
    if (!['downLoadWORD', 'downLoadPDF', 'export-ssm', 'export-txt', 'export-md', 'export-pdf', 'export-svg', 'export-png', 'export-json', 'export-xmind'].includes(item.type)) {
        clickTopBar.value = false
    }
    if (!item.isArrow) {
        hidePopover.value = false
    }
    switch (item.type) {
        case 'addTag':
            tagPopover.value = true
            labelLoading.value = true
            tagRef.value = moreActionButRef.value[item.type]
            labelList.value = []
            getLabel()
            tagListRef.value.wrapRef.addEventListener("scroll", (e: { target: { scrollTop: any; scrollHeight: any; clientHeight: any; }; }) => {
                const scrollTop = e.target.scrollTop
                const scrollHeight = e.target.scrollHeight
                const clientHeight = e.target.clientHeight
                if (
                    scrollTop > scrollHeight - clientHeight - 10 &&
                    scrollTop > tagScrollTop.value &&
                    !moreLoading.value && labelPage.value.current < Math.ceil(labelPage.value.total / labelPage.value.size)
                ) {
                    labelPage.value.current++
                    getLabel()
                }
                tagScrollTop.value = scrollTop
            })
            break
        case 'edit':
            hidePopover.value = false
            let editorType = editType(popoverData.value)
            if (editorType == 'directory') {
                createFolderRef.value.init('edit', popoverData.value, 'add_directory')
            } else {
                knowStore.setBackPage({
                    fromPage: knowledgeType.value,
                    docId: popoverData.value.id,
                    knowId: popoverData.value.knowledgeId,
                    dcLibrary: dcLibrary.value,
                    enterFolderId: enterFolderId.value,
                    breadPath: breadPath.value,
                }, O.uniqueId(knowledgeType.value + '-' + popoverData.value.knowledgeId + '-' + popoverData.value.id))
                if (editorType == 'editor') {
                    proxy.$openUrl(`/#/editor?knowId=${popoverData.value.knowledgeId}&docId=${popoverData.value.id}&fromId=${knowledgeType.value == 'my' ? 1 : 0}`, '_blank')
                } else if (editorType == 'office') {
                    proxy.$openUrl(`/#/editorOffice?knowId=${popoverData.value.knowledgeId}&docId=${popoverData.value.id}&fromId=${knowledgeType.value == 'my' ? 1 : 0}`, '_blank')
                }
            }
            break
        case 'reName':
            reNameRef.value.init(popoverData.value)
            break
        case 'download':
            if (item.isArrow) {
                downloadButPopoverRef.value = moreActionButRef.value[item.type]
                downloadActionList.value.forEach((item) => {
                    item.show = item.showType == popoverData.value.type
                })
                downloadPopover.value = true
            } else {
                if (['document_map', 'document_html', 'document_xlsx', 'xmind'].indexOf(popoverData.value.type) == -1) {
                    sourceFileDownload(popoverData.value)
                } else {
                    downloadFileFun(popoverData.value, '')
                }
            }
            break
        case 'del':
            hidePopover.value = false
            let delTitle = $t('message.confirm.delFileTitle'), delMess = $t('message.confirm.delFielContent')
            if (popoverData.value.type == 'directory') {
                delTitle = $t('message.confirm.delFolderTitle')
                delMess = $t('message.confirm.delFolderContent')
            }
            proxy.$confirm(delMess, delTitle, {
                confirmButtonText: $t('message.buttons.submit'),
                cancelButtonText: $t('message.buttons.cancal'),
                type: 'warning'
            }).then(() => {
                dclibRecycle(popoverData.value.id).then(res => {
                    if (res.data.code == 0) {
                        proxy.$onePrompt.$oneNotify({
                            title: $t('message.prompt'),
                            message: $t('message.message.delSuccess'),
                            position: 'bottom-right',
                            type: "success"
                        })
                        treeRef.value.remove(popoverData.value.id)
                    }
                })
            })
            break;
        case 'copy':
            let isFoler = `&knId=${popoverData.value.knowledgeId}&type=${popoverData.value.type}&fileName=${popoverData.value.fileName}&nameSuffix=${popoverData.value.nameSuffix}`
            if (enterFolderId.value) {
                isFoler = '&folderId=' + enterFolderId.value
            }
            copyText(window.location.origin + "/#" + route.path + "?docId=" + popoverData.value.id + isFoler, () => {
                proxy.$onePrompt.$oneNotify({
                    title: $t('message.prompt'),
                    message: $t('message.message.copySuccess'),
                    position: 'bottom-right',
                    type: "success"
                })
            })
            break
        case 'move':
            selectKnowRef.value.init()
            break;
        case 'share':
            // shareVisible.value = true
            // shareInfo.value = popoverData.value
            // nextTick(() => {
            //     if (!shareInfo.value.shareTimeType) {
            //         shareInfo.value.shareTimeType = 'PERPETUAL'
            //     }
            //     shareDialogRef.value.init()
            // })
            break
        case 'collect':
            hidePopover.value = false
            sendCollect(popoverData.value.id)
            break
        case 'add':
            addButPopoverRef.value = moreActionButRef.value[item.type]
            addPopover.value = true
            break
        case 'upload':
            uploadButPopoverRef.value = moreActionButRef.value[item.type]
            uploadPopover.value = true
            break
        case 'uploadFile':
            proxy.$eventBus.$emit("uploadFile", 'file', ['directory', 'knowledge'].indexOf(popoverData.value.type) != -1 ? popoverData.value.id : popoverData.value.parentId)
            // uploadBoxRef.value.fileUpload('file',['directory','knowledge'].indexOf(popoverData.value.type)!=-1?popoverData.value.id:popoverData.value.parentId)
            break;
        case 'uploadFolder':
            proxy.$eventBus.$emit("uploadFile", 'folder', ['directory', 'knowledge'].indexOf(popoverData.value.type) != -1 ? popoverData.value.id : popoverData.value.parentId)
            // uploadBoxRef.value.fileUpload('folder',['directory','knowledge'].indexOf(popoverData.value.type)!=-1?popoverData.value.id:popoverData.value.parentId)
            break;
        case "setting":
            if (['directory', 'knowledge'].indexOf(popoverData.value.type) == -1) {
                proxy.$openDocSet({
                    docInfo: popoverData.value,
                })
            } else if (['directory'].indexOf(popoverData.value.type) != -1) {
                proxy.$openDirSet({
                    docInfo: popoverData.value,
                })
            }
            break;
        case 'document_html':
        case 'document_map':
        case 'document_xlsx':
        case 'document_flow':
        case 'md':
        case 'xmind':
        case 'office_doc':
        case 'office_xlsx':
        case 'office_ppt':
        case 'office_csv':
            proxy.$eventBus.$emit("createKnowFile", item.type, popoverData.value, item.label)
            break
        case "downLoadWORD":
            downloadFileFun(!clickTopBar.value ? popoverData.value : checkNode.value, 'docx')
            clickTopBar.value = false
            break
        case 'downLoadPDF':
            downloadFileFun(!clickTopBar.value ? popoverData.value : checkNode.value, 'pdf')
            clickTopBar.value = false
            break
        case 'export-xmind':
        case 'export-txt':
        case 'export-md':
        case 'export-pdf':
        case 'export-svg':
        case 'export-png':
        case 'export-json':
        case 'export-smm':
            // downloadFileFun(!clickTopBar.value ? popoverData.value : checkNode.value, item.type)
            clickTopBar.value = false
            break
        case 'unZip':
            fileDictoryDec({
                id: popoverData.value.id
            }).then((res: any) => {
                if (res.data.code == 0) {
                    proxy.$notify({
                        title: $t('message.downloadTitle'),
                        message: $t('message.message.unZipSuccess'),
                        type: 'success',
                        position: 'bottom-right'
                    })
                    // init()
                }
            })
            break
        default:
            proxy.$eventBus.$emit('openFolder', item.type, popoverData.value)
            break;
    }
}

function onClickOutside() {
    moreActionButRef.value = {}
    if (!tagPopover.value) {
        hidePopover.value = false
    }
    addPopover.value = false
    uploadPopover.value = false
    downloadPopover.value = false
}

function setMoreTypeRef(el: any, data: any) {
    if (el) {
        moreActionButRef.value[data.type] = el
    }
}

const navList = ref<any[]>(NAV_LIST)
navList.value = navList.value.map((item: any) => ({ ...item, level: 1, key: item.path }))

const setNavList = ref(SET_NAV_LIST)
const silderScroll = ref()
const logoImg = computed(() => {
    return (!props.brevity ? userStore.tenantInfo?.logo || logo : userStore.tenantInfo?.icon || icon)
})
const isActiveItem = computed(() => {
    let index = -1
    getCurrentNavList.value.forEach((element: any, i: number) => {
        if (element.path == route.path) {
            index = i
        }
        if (element.isReq && route.path.indexOf(element.path) != -1) {
            index = i
        }
    });
    return index
})

const isLogin = computed(() => {
    return userStore.access_token
})
const getCurrentNavList = computed<any[]>(() => {
    let arr: any[] = []
    if (route.path.indexOf('/setting') != -1) {
        arr = setNavList.value
    } else {
        arr = navList.value
    }
    arr.forEach((item) => {
        item.label = $t(item.langLabel)
    })
    return arr
})


const formatTreeList = (l: any[], keyPrefix: 'my-' | 'all-' = 'my-', level: number) => {
    return l.map((v: any) => ({
        ...v, level, label: v.name, key: keyPrefix + v.id, children: [{ label: '暂无数据', key: generateUUID() }]
    }))
}

const nodeExpand = (d: any) => {
    // console.log('nodeExpand', d, node)
    const { children, id, key, level } = d
    if (level !== 1 && children && children.length === 1 && !children[0].id) {
        treeRef.value?.updateKeyChildren(key, [])
        getLibTree({ id }).then(res => {
            const { data, code } = res.data
            const arr = data.data.map((v: any) => v.id)
            // console.log('nodeExpand', arr, 'level:', level + 1)
            dcLibrary.value = data.dcLibrary
            if (code == 0 && !arr.includes(id)) {
                if (data.data.length) {
                    treeRef.value?.updateKeyChildren(key, formatTreeList(data.data, key.startsWith('my-') ? 'my-' : 'all-', level + 1))
                }
            }
        })
    }
}

const setSelect = () => {
    nextTick(() => {
        const k = treeRef.value?.getCurrentKey()
        const { type, id } = route.params
        if (!k && ['all', 'my'].includes(type as string) && id) {
            treeRef.value?.setCurrentKey(`${type}-${id}`)
        }
    })
}

const treeRef = ref<InstanceType<typeof ElTree> | null>(null)
watch(() => route.path, (n, o) => {
    if (n !== o) {
        for (let i = 0; i < getCurrentNavList.value.length; i++) {
            if (n === getCurrentNavList.value[i].path) {
                nextTick(() => {
                    treeRef.value?.setCurrentKey(n)
                })
                return
            }
        }
    }
}, {
    immediate: true
})

const isHideCol = computed(() => {
    return route.path.indexOf('/setting') != -1
})
const isCheckKnow = computed(() => {
    return route.params.id
})
const uniId = ref<string>()
const knowledgeId = ref('')
onMounted(() => {
    knowledgeId.value = route.params.id as string
    uniId.value = O.uniqueId(knowledgeType.value + '-' + knowledgeId.value)
    dcLibrary.value = knowStore.dcLibrary[uniId.value] || {}
    knowledgeType.value = route.params.type as string
    if (isLogin.value) {
        getAllKnowledgeList()
        getMyKnowledgeLit()
    }
    listenerKnowledgeList()
})
watch(() => route.params, (newV, oldV) => {
    if (!(newV.id || newV.knId)) {
        enterFolderId.value = ''
        breadPath.value = []
        dcLibrary.value = {
            name: '',
            dcIdentifying: []
        }
    }
    if (newV.id != oldV.id && (newV.id || newV.knId)) {
        knowledgeId.value = (newV.id || newV.knId) as string
        enterFolderId.value = ''
        breadPath.value = []
        dcLibrary.value = {
            name: '',
            dcIdentifying: []
        }
        morebuttonRefs.value = {}
        moreActionButRef.value = {}
        currAction.value = {}
    }
    knowledgeType.value = newV.type as string
})
function changeItemOpen(item: { isOpen: boolean; }) {
    item.isOpen = !item.isOpen
    setTimeout(() => {
        silderScroll.value.update()
    }, 400)
}

function listenerKnowledgeList() {
    proxy.$eventBus.$on('knowledgeList', (val: any, type: any) => {
        if (type == 'my') {
            if (JSON.stringify(navList.value[2].list) != JSON.stringify(val)) {
                navList.value[2].list = formatTreeList(val, 'my-', 2)
                navList.value[2].children = navList.value[2].list
                setSelect()
            }
        } else {
            if (JSON.stringify(navList.value[1].list) != JSON.stringify(val)) {
                navList.value[1].list = formatTreeList(val, 'all-', 2)
                navList.value[1].children = navList.value[1].list
                setSelect()
            }
        }
    })
    proxy.$eventBus.$on('addList', (type: string, data: any) => {
        let index = -1
        if (type == 'all') {
            index = 1
        }
        if (type == 'my') {
            index = 2
        }
        if (index != -1) {
            addData(data, index)
        } else {
            addData(data, 1)
            addData(data, 2)
        }
    })
}

function addData(data: any, index: number) {
    navList.value[index].list.push(data)
    let topArr = navList.value[index].list.filter((item: { isTopping: any; }) => {
        return item.isTopping
    })
    let notopArr = navList.value[index].list.filter((item: { isTopping: any; }) => {
        return !item.isTopping
    })
    let notopSort = notopArr.sort((a: { createTime: string | number | Date; }, b: { createTime: string | number | Date; }) => {
        let aT = new Date(a.createTime).getTime()
        let bT = new Date(b.createTime).getTime()
        return bT - aT
    })
    navList.value[index].list = [...topArr, ...notopSort]
}

function getAllKnowledgeList() {
    getDcLibraryList({
        size: 1000,
        current: 1,
    }).then(res => {
        if (res.data.code == 0) {
            navList.value[1].list = formatTreeList(res.data.data.records, 'all-', 2)
            navList.value[1].children = navList.value[1].list
            setSelect()
        }
    }).finally(() => {
    })
}

function getMyKnowledgeLit() {
    knowledgesOwner({
        size: 1000,
        current: 1,
    }).then(res => {
        if (res.data.code == 0) {
            navList.value[2].list = formatTreeList(res.data.data.records, 'my-', 2)
            navList.value[2].children = navList.value[2].list
            setSelect()
        }
    }).finally(() => {
    })
}

function goHome() {
    router.push({
        path: '/index'
    })
}

function goToKnow(cItem: any, item: any, index: any) {
    if (isCheckKnow.value == cItem.id && index == isActiveItem.value) return
    router.push({
        path: `${item.path}/${cItem.id}`
    })
}

function toPath(item: { path: any; }) {
    if (item.path) {
        router.push({
            path: item.path
        })
    }
}

const nodeClick = (data: any) => {
    if (data.level === 1) {
        toPath(data)
    } else if (data.level === 2) {
        let item = null
        let index = 0
        const d = getCurrentNavList.value as any
        for (let i = 0; i < d.length; i++) {
            const c = d[i].children
            if (c && c.length) {
                for (let j = 0; j < c.length; j++) {
                    if (c[j].key === data.key) {
                        item = d[i]
                        index = i
                        break
                    }
                }
            }
            if (item !== null) {
                break
            }
        }
        // console.log('nodeClick:', data, 'item:', item, 'index', index)
        // debugger
        goToKnow(data, item, index)
    } else {
        proxy.$eventBus.$emit('select-doc', data)
    }
}

function goLogin() {
    router.push({
        path: '/login',
        query: {
            redict_url: encodeURIComponent(route.fullPath)
        }
    })
}

</script>
<style lang="scss">
.silder-nav-body {
    .el-tree {
        --el-fill-color-blank: transparent;
        --el-tree-node-content-height: 36px !important;
    }
}
</style>
<style lang="scss" scoped>
.silder-bar-box {
    padding: 12px 0px 12px 12px;
    box-sizing: border-box;
    background: #F5F6F7;
    height: 100%;
    box-sizing: border-box;
    width: 100%;
    overflow: hidden;

    .logo-img {
        height: 49px;
        width: 200px;
        display: flex;
        align-items: center;
        overflow: hidden;
        padding-right: 12px;
        cursor: pointer;

        img {
            width: 100%;
        }

        .logo-image {
            display: block;
            width: 200px;
            height: 50px;
            overflow: hidden;
            cursor: pointer;
            background-size: contain;
            background-repeat: no-repeat;
            background-position: 50%;
        }
    }

    .small-img {
        width: 100%;
        height: 49px;
        justify-content: center;
        padding: 12px 12px 12px 0px;
        box-sizing: border-box;

        img {
            width: 30px;
            height: 30px;
        }

        .logo-image {
            width: 30px;
            height: 30px;
        }
    }

    .silder-nav-body {
        margin-top: 15px;
        height: calc(100% - 64px);

        .custom-tree-node {
            .svg-icon {
                width: 15px;
                height: 15px;
                margin-right: 8px;
            }
        }

        .el-tree {
            height: 100%;
            padding-right: 4px;

            ::v-deep(.el-tree-node__content) {
                height: 52px;
                border-radius: 4px;

                &:hover {
                    background: #DDEAFF !important;
                }
            }

            ::v-deep(.is-current>.el-tree-node__content) {
                background: #DDEAFF !important;
            }

            ::v-deep(.el-tree-node__content:has(.custom-active)) {
                background: #DDEAFF !important;
            }

            ::v-deep(.custom-active) {
                .action-box {
                    .share {
                        visibility: hidden !important;
                    }

                    .more {
                        visibility: visible !important;
                        z-index: 2;
                        color: #1E6FFF;
                        background: #EDF4FF;
                        border-radius: 4px 4px 4px 4px;
                    }
                }
            }

            ::v-deep(.custom-tree-node-child) {
                display: flex;
                align-items: center;
                //padding-left: 16px;
                width: 180px;

                .node-info {
                    margin-left: 12px;
                    width: calc(100% - 30px);
                    overflow: hidden;

                    .name {
                        font-size: 14px;
                        color: #363B4C;
                        width: calc(100% - 0px);
                        text-overflow: ellipsis;
                        overflow: hidden;
                        white-space: nowrap;
                    }

                    .time {
                        width: calc(100% - 0px);
                        font-size: 12px;
                        color: #6F7588;
                        text-overflow: ellipsis;
                        overflow: hidden;
                        white-space: nowrap;
                    }
                }

                &:hover {
                    .action-box {
                        .share {
                            visibility: hidden;
                        }

                        .more {
                            visibility: visible;
                            z-index: 2;
                        }
                    }

                    .no-auth-aciton-box {
                        .share {
                            visibility: visible;
                        }

                        .more {
                            visibility: hidden;
                            z-index: 2;
                        }
                    }
                }

                .action-box {
                    width: 20px;
                    height: 20px;
                    cursor: pointer;
                    border: none;
                    position: relative;

                    .action-icon {
                        width: 20px;
                        height: 20px;
                        outline: none !important;
                    }

                    .share {
                        visibility: visible;
                    }

                    .more {
                        font-size: 20px;
                        position: absolute;
                        left: 0px;
                        visibility: hidden;

                        &:hover {
                            background: #EDF4FF;
                            border-radius: 4px 4px 4px 4px;
                            color: #1E6FFF;
                        }
                    }
                }

                .svg-icon {
                    width: 20px;
                    height: 20px;
                }
            }
        }

        // padding-right: 12px;
        .silder-item {
            white-space: nowrap;
            height: 36px;
            display: flex;
            align-items: center;
            padding: 0px 13px;
            box-sizing: border-box;
            cursor: pointer;
            margin-right: 12px;

            &:hover {
                background-color: #eeeff0;
            }

            .icon-list {
                width: 14px;
                height: 14px;
                margin-right: 9px;
                display: flex;
                align-items: center;

                .icon {
                    width: 14px;
                    height: 14px;
                    cursor: pointer;
                }
            }

            .title {
                display: flex;
                align-items: center;

                .svg-icon {
                    width: 15px;
                    height: 15px;
                    margin-right: 8px;
                }

                ::v-deep(.el-tooltip__trigger) {
                    display: flex;
                    align-items: center;
                }

                span {
                    color: #363B4C;
                    font-size: 14px;
                    @include SourceHanSansCN-Regular
                }
            }
        }

        .silder-item+.silder-item {
            margin-top: 6px;
        }

        .silder-item-active {
            background: #DDEAFF !important;
            border-radius: 4px;

            .title {
                span {
                    color: #1E6FFF !important;
                }
            }
        }

        .list-box {
            display: grid;
            flex-direction: column;
            grid-template-rows: 0fr;
            overflow: hidden;
            transition: all 0.4s;
            margin-right: 12px;

            .list-items {
                overflow: hidden;

                .silder-item-active {
                    span {
                        color: #1E6FFF !important;
                    }
                }

                .list-item {
                    display: flex;
                    align-items: center;
                    height: 36px;
                    font-size: 14px;
                    color: #363B4C;
                    padding-left: 42px;
                    cursor: pointer;

                    &:hover {
                        background-color: #eeeff0;
                    }

                    .svg-icon {
                        min-width: 15px;
                        width: 15px;
                        height: 15px;
                        margin-right: 8px;
                    }

                    span {
                        text-overflow: ellipsis;
                        overflow: hidden;
                        white-space: nowrap;
                    }

                    // transition: all 0.5s;
                    // grid-template-rows: 0fr;
                    // visibility: hidden;
                    // overflow: hidden;
                }
            }

        }

        .list-box-open {
            grid-template-rows: 1fr;
        }
    }

    .no-login-box {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        height: 100%;
        width: 100%;
        padding-right: 12px;

        img {
            width: 100%;
        }

        .login-title {
            color: #363B4C;
            font-size: 16px;
        }

        .login-tips {
            color: #6F7588;
            font-size: 14px;
            margin-top: 12px;
            margin-bottom: 32px;
        }

        .login-button {
            width: 130px;
        }
    }
}
</style>